package com.linkage.jz.bankruptcy.activity.RegistLogin;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.register.BindAccountActivity;
import com.linkage.seapeak.activity.register.RegisterActivity;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.pojo.QQAuthData;
import com.linkage.seapeak.pojo.WxAuthData;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public class PhoneLoginActivity extends BaseWhiteActivity implements OnClickListener {
    private static final String TAG = AccountLoginActivity.class.getSimpleName();

    private ShapeLoadingDialog shapeLoadingDialog;

    TextView btn_login, getcode;
    EditText et_username, et_vcode;
    View ll_accountlogin, ll_register;
    MyCountDownTimer myCountDownTimer;
    View wxlogin, qqlogin;

    public static void start(Context context) {
        Intent intent = new Intent(context, PhoneLoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_login, "手机快捷登录");
        initview();
        shapeLoadingDialog = new ShapeLoadingDialog(this);
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层
        myCountDownTimer = new MyCountDownTimer(60000, 1000);

        et_username = findViewById(R.id.et_username);
        btn_login = findViewById(R.id.btn_login);
        et_vcode = findViewById(R.id.et_vcode);
        ll_accountlogin = findViewById(R.id.ll_accountlogin);
        ll_register = findViewById(R.id.ll_register);
        getcode = findViewById(R.id.getcode);
        wxlogin = findViewById(R.id.wx_login);
        qqlogin = findViewById(R.id.qq_login);

        btn_login.setOnClickListener(this);
        ll_accountlogin.setOnClickListener(this);
        ll_register.setOnClickListener(this);
        getcode.setOnClickListener(this);
        wxlogin.setOnClickListener(this);
        qqlogin.setOnClickListener(this);

        et_username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showSave();
                showCode();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        et_vcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                showSave();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        showSave();
        showCode();
    }


    private void showCode()
    {
        String str1 =  et_username.getText().toString().trim();
        if(str1.equalsIgnoreCase(""))
        {
            getcode.setClickable(false);
            getcode.setTextColor(getResources().getColor(R.color.btnosel));
        }else{
            getcode.setClickable(true);
            getcode.setTextColor(getResources().getColor(R.color.btsel));
        }
    }

    private void showSave()
    {
        String str1 =  et_username.getText().toString().trim();
        String str2 =  et_vcode.getText().toString().trim();

        if(!str1.equalsIgnoreCase("") && !str2.equalsIgnoreCase("")
                )
        {

            btn_login.setClickable(true);
            btn_login.setBackgroundColor(getResources().getColor(R.color.btsel));
        }else{
            btn_login.setClickable(false);
            btn_login.setBackgroundColor(getResources().getColor(R.color.btnosel));
        }


    }


    @Override
    public void onClick(View view) {
        String phone = "";
        String code = "";
        String pwd = "";
        switch (view.getId()) {
            case R.id.btn_login:
                //返回
                phone = et_username.getText().toString();
                code = et_vcode.getText().toString();
                if ("".equalsIgnoreCase(phone)) {
                    showToast("手机号码不能为空");
                    return;
                }
                if ("".equalsIgnoreCase(code)) {
                    showToast("验证码不能为空");
                    return;
                }
                LoginUser(phone, code, pwd);
                break;
            case R.id.ll_accountlogin:
                AccountLoginActivity.start(this);
                finish();
                break;
            case R.id.ll_register:
                RegisterActivity.start(this);
                finish();
                break;
            case R.id.getcode:
                phone = et_username.getText().toString();
                if ("".equalsIgnoreCase(phone)) {
                    showToast("手机号码不能为空");
                    return;
                } else {

                    getSMSCode(phone);

                }
                break;
            case R.id.wx_login:
                authLogin(Wechat.NAME);
                break;
            case R.id.qq_login:
                authLogin(QQ.NAME);
                break;
            default:
                break;
        }
    }

    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            getcode.setClickable(false);
            getcode.setText(l / 1000 + "秒");

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            getcode.setText("重新获取");
            //设置可点击
            getcode.setClickable(true);
        }
    }

    public void LoginUser(String mobile, String code, String pwd) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }
        String appInfoId = SPUtils.getInstance(Consts.SPNAME).getString("appInfoId", "");
        if ("".equalsIgnoreCase(appInfoId)) {
            saveCid();
//            Toast.makeText(AccountLoginActivity.this, "没有cid", Toast.LENGTH_SHORT).show();

            return;
        }

        Log.d(TAG, "LoginUser:  appInfoId " +appInfoId );

        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() / 1000 + "";

//        saveCid = "";

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("mobile", mobile)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("password", pwd)
                .add("smsCaptcha", code)
                .add("appInfoId", appInfoId)
                .add("loginType", "1")
                .build();

        String url = Consts.WEBURL_LOGIN;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        Gson gson = new Gson();
                        JSONObject data = object.getJSONObject("data");

                        SPUtils.getInstance(Consts.SPNAME).put("userInfo", data.toString());


                        String userToken = data.getString("userToken");

                        SPUtils.getInstance(Consts.SPNAME).put("userToken", userToken);
//                        SPUtils.getInstance(Consts.SPNAME).put("userInfobaseUrl",data.optString("baseUrl"));


                        LoginInfo info = gson.fromJson(data.optString("userInfo"), LoginInfo.class);
//                        Hawk.put(HawkKey.LOGINDETIAL, info);
                        SPUtils.getInstance(Consts.SPNAME).put("userId", info.getId());
                        BankruptcyApp.loginInfo = info;
                        BankruptcyApp.userToken = userToken;
                        MainActivity.start(PhoneLoginActivity.this);
                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showToast("登录失败");

                            }

                        });
                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public void getSMSCode(String mobile) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
//        params.put("appid",Consts.APPID);
//        params.put("nonce", rom);
//        params.put("timestamp", timestamp);
//
//        String sign = SignUtil.createSign(Consts.APPKEY,params);

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("mobile", mobile)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("reg", "false")
                .add("source", "0")
                .build();

        String url = Consts.WEBURL_SMSCAPTCHA;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
//                        Toast.makeText(PhoneLoginActivity.this,"请求成功，请查看短信"+object.optString("data"),Toast.LENGTH_SHORT).show();
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                myCountDownTimer.start();
                                Toast.makeText(PhoneLoginActivity.this, "请求成功，请查看短信" + object.optString("data"), Toast.LENGTH_SHORT).show();
                            }

                        });

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showToast("请求失败:"+object.optString("msg"));
                            }

                        });
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    /**
     * 授权登录
     *
     * @param name
     */
    public void authLogin(final String name) {
        final Platform authPlatform = ShareSDK.getPlatform(name);
        ShareSDK.setActivity(this);//抖音登录适配安卓9.0
        //回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
        authPlatform.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                arg2.printStackTrace();
                showToast("授权失败！");
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> hashMap) {
                //输出所有授权信息
                final String authData = arg0.getDb().exportData();//取到所有数据
                Log.e("zhong", "授权 onComplete: " + authData);
                if (name.equals(QQ.NAME)) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Log.e("========", "qq");
                            QQAuthData data = new Gson().fromJson(authData, QQAuthData.class);
                            qqLogin(data);
                        }

                    });
                } else {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Log.e("========", "wx1");
                            //更新UI
                            WxAuthData data = new Gson().fromJson(authData, WxAuthData.class);
                            Log.e("========", "ww2");
                            wxLogin(data);

                        }

                    });
                }
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                showToast("取消授权！", ToastUtil.TOAST_TYPE.NOSHOW);
            }
        });
        //authorize与showUser单独调用一个即可
        authPlatform.authorize();//要功能不要数据，在监听oncomplete中不会返回用户数据
    }

    /**
     * QQ 登录
     *
     * @param data
     */
    public void qqLogin(final QQAuthData data) {
        String appInfoId = SPUtils.getInstance(Consts.SPNAME).getString("appInfoId", "");
        if ("".equalsIgnoreCase(appInfoId)) {
            saveCid();

            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        Log.d(TAG, "qqLogin:  appInfoId " +appInfoId );

        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = getTokenRequest()
                .add("openid", data.getUserID())
                .add("nickname", data.getNickname())
                .add("figureurl_qq", data.getIcon())
                .add("unionid", data.getUnionid())
                .add("gender", data.getGender().equals("0") ? "男" : "女")
                .add("pay_token", data.getPay_token())
                .add("secret", data.getSecret())
                .add("userID", data.getUserID())
                .add("expiresTime", data.getExpiresTime() + "")
                .add("token", data.getToken())
                .add("expiresIn", data.getExpiresIn() + "")
                .add("pfkey", data.getPfkey())
                .add("pf", data.getPf())
                .add("secretType", data.getSecretType())
                .add("iconQzone", data.getIconQzone())
                .add("icon", data.getIcon())
                .add("appInfoId",appInfoId)
                .build();

        Request request = new Request.Builder()
                .url(Consts.WEBURL_QQ_LOGIN)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                final String str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            shapeLoadingDialog.dismiss();
                            JSONObject object = new JSONObject(str);
                            Log.i(TAG, "绑定的账号信息 onResponse: " + str);
                            JSONObject info = object.getJSONObject("data");

                            if (info != null) {
                                if (info.has("bind") && info.optInt("bind") == 0) {
                                    Log.i(TAG, "run: 已绑定QQ");
                                    LoginInfo userInfo = new Gson().fromJson(info.getString("userInfo"), LoginInfo.class);
//                                    Hawk.put(HawkKey.USERTOKEN, info.getString("userToken"));
//                                    Hawk.put(HawkKey.LOGINDETIAL, userInfo);
                                    BankruptcyApp.userToken = info.getString("userToken");

                                    BankruptcyApp.loginInfo = userInfo;
                                    SPUtils.getInstance(Consts.SPNAME).put("userInfo", object.getString("data"));
                                    SPUtils.getInstance(Consts.SPNAME).put("userToken", info.getString("userToken"));
                                    SPUtils.getInstance(Consts.SPNAME).put("userId", userInfo.getId());

                                    finish();
                                } else {
                                    Log.i(TAG, "run: 未绑定QQ");
                                    Intent intent = new Intent(PhoneLoginActivity.this, BindAccountActivity.class);
                                    intent.putExtra("data", data);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    /**
     * wx 登录
     *
     * @param data
     */
    public void wxLogin(final WxAuthData data) {
        String appInfoId = SPUtils.getInstance(Consts.SPNAME).getString("appInfoId", "");
        if ("".equalsIgnoreCase(appInfoId)) {
            saveCid();

            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();

        Log.d(TAG, "wxLogin:  appInfoId " +appInfoId );

        Log.e("========", "ww3");
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = getTokenRequest()
                .add("wxid",data.getOpenid())
                .add("openid", data.getOpenid())
                .add("nickname", data.getNickname())
                .add("figureurl_qq", data.getIcon())
                .add("unionid", data.getUnionid())
                .add("gender", data.getGender().equals("0") ? "男" : "女")
                .add("userID", data.getUserID())
                .add("expiresTime", data.getExpiresTime() + "")
                .add("token", data.getToken())
                .add("expiresIn", data.getExpiresIn() + "")
                .add("headimgurl", data.getIcon())
                .add("icon", data.getIcon())
                .add("appInfoId",appInfoId)
                .build();

        Request request = new Request.Builder()
                .url(Consts.WEBURL_WX_LOGIN)
                .post(requestBody)
                .build();

        Log.e("========", "ww4");
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                final String str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Log.e("========", "ww5");
                            shapeLoadingDialog.dismiss();
                            JSONObject object = new JSONObject(str);
                            Log.i(TAG, "绑定的账号信息 onResponse: " + str);
                            if(object.optInt("code") == 0) {
                                Log.e("========", "ww6");
                                JSONObject info = object.getJSONObject("data");

                                if (info != null) {
                                    Log.e("========", "ww7");
                                    if (info.has("bind") && info.optInt("bind") == 0) {
                                        Log.i(TAG, "run: 已绑定WX");
                                        LoginInfo userInfo = new Gson().fromJson(info.getString("userInfo"), LoginInfo.class);
//                                    Hawk.put(HawkKey.USERTOKEN, info.getString("userToken"));
//                                    Hawk.put(HawkKey.LOGINDETIAL, userInfo);
                                        BankruptcyApp.userToken = info.getString("userToken");

                                        BankruptcyApp.loginInfo = userInfo;
                                        SPUtils.getInstance(Consts.SPNAME).put("userInfo", object.getString("data"));
                                        SPUtils.getInstance(Consts.SPNAME).put("userToken", info.getString("userToken"));
                                        SPUtils.getInstance(Consts.SPNAME).put("userId", userInfo.getId());

                                        finish();
                                    } else {
                                        Log.i(TAG, "run: 未绑定WX");
                                        Intent intent = new Intent(PhoneLoginActivity.this, BindAccountActivity.class);
                                        intent.putExtra("data", data);
                                        startActivity(intent);
                                        finish();
                                    }
                                }
                            }else{
                                showToast("失败：" + object.optString("msg"));
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    public void saveCid() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }
        shapeLoadingDialog.setLoadingText("提交信息中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();


//        LoginUser(mobile, code, pwd);
        String saveCid = SPUtils.getInstance(Consts.SPNAME).getString("saveCid", "");
        OkHttpClient okHttpClient = new OkHttpClient();
        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")
                .add("appVersion", "0.0.1")
                .add("cid", saveCid)
                .add("os", "0")
//                .add("osVersion", "123")
//                .add("model", "123")
//                .add("manufacturer", "123")
                .add("osVersion", Build.VERSION.SDK)
                .add("model", android.os.Build.MODEL)
                .add("manufacturer", android.os.Build.MANUFACTURER)
                .build();

        String url = Consts.WEBURL_SAVECID;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();


                shapeLoadingDialog.dismiss();
                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        Gson gson = new Gson();
                        JSONObject data = object.getJSONObject("data");
                        String cid = data.optString("appInfoId");
//                        BankruptcyApp.tokeninfo = info;
//                        String saveCid = SPUtils.getInstance(Consts.SPNAME).getString("saveCid","");
//                        if("".equalsIgnoreCase(saveCid))
//                        {
                        SPUtils.getInstance(Consts.SPNAME).put("appInfoId", cid);
//                        }
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                            }

                        });
                    } else {

                    }

                    str = "";
                } catch (Exception ex) {

                    ex.printStackTrace();
                }
            }
        });


    }

}

